#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# @Time    : 2025/3/31 14:26
# @Author  : 梁满仓
# @File    : breaking_through_ma7_first_of_600519.py
# @Software: PyCharm

import akshare as ak
import pandas as pd


def get_first_ma7_breakthrough(stock_code, start_date='20220101', end_date='20241231'):
    """
    获取股票首次突破7日均线并且第二日站稳7日均线的时间和收盘价

    参数:
        stock_code: 股票代码，例如 '600519' (贵州茅台)
        start_date: 开始日期，默认为 '2022-01-01'
        end_date: 结束日期，默认为 '2024-12-31'

    返回:
        字典，包含突破日期和收盘价，如果没有找到则返回None
    """
    print('stock_code:', stock_code)
    # 获取股票历史数据
    try:
        stock_df = ak.stock_zh_a_hist(symbol=stock_code, period="daily", start_date=start_date, end_date=end_date, adjust="hfq")
        #stock_df = ak.stock_zh_a_hist(symbol="600519", period="daily", start_date="20220101", end_date="20241231", adjust="hfq")
    except Exception as e:
        print(f"获取股票数据失败: {e}")
        return None

    print('打印stock_df')
    print(stock_df)
    # 确保数据按日期升序排列
    stock_df = stock_df.sort_values('日期')

    # 计算7日均线
    stock_df['MA7'] = stock_df['收盘'].rolling(window=7).mean()

    # 初始化标志列
    stock_df['突破'] = False
    stock_df['站稳'] = False

    # 找出突破和站稳的点
    for i in range(1, len(stock_df)):
        # 前一天收盘价低于7日均线，当天收盘价高于7日均线 - 突破
        if stock_df.iloc[i - 1]['收盘'] < stock_df.iloc[i - 1]['MA7'] and stock_df.iloc[i]['收盘'] > stock_df.iloc[i][
            'MA7']:
            stock_df.at[stock_df.index[i], '突破'] = True

            # 检查第二天是否站稳 (收盘价仍在7日均线之上)
            if i + 1 < len(stock_df):
                if stock_df.iloc[i + 1]['收盘'] > stock_df.iloc[i + 1]['MA7']:
                    stock_df.at[stock_df.index[i + 1], '站稳'] = True

                    # 返回首次满足条件的记录
                    breakthrough_date = stock_df.iloc[i]['日期']
                    breakthrough_close = stock_df.iloc[i]['收盘']
                    confirm_date = stock_df.iloc[i + 1]['日期']
                    confirm_close = stock_df.iloc[i + 1]['收盘']

                    return {
                        '突破日期': breakthrough_date,
                        '突破收盘价': breakthrough_close,
                        '确认日期': confirm_date,
                        '确认收盘价': confirm_close,
                        '7日均线突破日值': stock_df.iloc[i]['MA7'],
                        '7日均线确认日值': stock_df.iloc[i + 1]['MA7']
                    }

    # 如果没有找到符合条件的记录
    print("在指定时间范围内未找到首次突破7日均线并站稳的记录")
    return None


# 示例使用
if __name__ == "__main__":
    stock_code = '600519'  # 贵州茅台
    result = get_first_ma7_breakthrough(stock_code)

    if result:
        print(f"股票 {stock_code} 首次突破7日均线并站稳的情况:")
        print(
            f"突破日期: {result['突破日期']}, 收盘价: {result['突破收盘价']:.2f}, 7日均线: {result['7日均线突破日值']:.2f}")
        print(
            f"确认日期: {result['确认日期']}, 收盘价: {result['确认收盘价']:.2f}, 7日均线: {result['7日均线确认日值']:.2f}")
    else:
        print(f"股票 {stock_code} 在指定时间内未满足条件")